from django.shortcuts import render, redirect
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required
from django.utils import timezone
from datetime import timedelta
from KeHu.models import KeHu
from ChanPin.models import Dingdan,Chanpin
from django.db.models import Sum
from django.contrib import messages
from django.views.generic import ListView, UpdateView, DeleteView, CreateView, DetailView
from django.contrib.auth.mixins import LoginRequiredMixin
from .models import new
import os
from django.conf import settings
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def upload_image(request):
    """图潘上传入口 编辑器插件用"""
    if request.method == "POST":
        file_obj = request.FILES['file']
        file_name_suffix = file_obj.name.split(".")[-1]
        if file_name_suffix not in ["jpg", "png", "gif", "jpeg", ]:
            return JsonResponse({"message": "错误的文件格式"})

        upload_time = timezone.now()
        path = os.path.join(
            settings.MEDIA_ROOT,
            'tinymce',
            str(upload_time.year),
            str(upload_time.month),
            str(upload_time.day)
        )
        # 如果没有这个路径则创建
        if not os.path.exists(path):
            os.makedirs(path)

        file_path = os.path.join(path, file_obj.name)

        file_url = f'{settings.MEDIA_URL}tinymce/{upload_time.year}/{upload_time.month}/{upload_time.day}/{file_obj.name}'

        if os.path.exists(file_path):
            return JsonResponse({
                "message": "文件已存在",
                'location': file_url
            })

        with open(file_path, 'wb+') as f:
            for chunk in file_obj.chunks():
                f.write(chunk)

        return JsonResponse({
            'message': '上传图片成功',
            'location': file_url
        })
    return JsonResponse({'detail': "错误的请求"})

@login_required
def home(request):
    if request.user.is_authenticated:#判断用户是否登录
        context = {
            'user': request.user,
            'active_page': "index",
            'new_customers_this_month': 0,  # 初始化为0，稍后进行计算
        }
        now = timezone.now()
        first_day_of_month = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
        first_day_of_next_month = (first_day_of_month + timedelta(days=31)).replace(day=1)
        end_of_month = first_day_of_next_month - timedelta(seconds=1)

        # 减少变量冗余，直接使用request.user
        new_customers_this_month = KeHu.objects.filter(
            addtime__gte=first_day_of_month,
            addtime__lte=end_of_month,
            admin_user=request.user
        ).count()

        # 合并重复查询
        dingdan_this_month = Dingdan.objects.filter(
            ddtime__gte=first_day_of_month,
            ddtime__lte=end_of_month,
            dduser=request.user
        )
        new_dingdan_this_month = dingdan_this_month.count()
        new_ddjine_this_month = dingdan_this_month.aggregate(total_ddjine=Sum('ddjine')).get('total_ddjine', 0)
        if new_ddjine_this_month is None:
            new_ddjine_this_month = 0

        # 初始化cbj总和为0
        total_cbj = 0  # 初始化cbj总和为0
        # 设定Decimal的上下文环境，以控制全局的精度和舍入方式
        # 这里设置为保留两位小数，使用四舍五入
        from decimal import Decimal, ROUND_HALF_UP
        from decimal import getcontext
        getcontext().prec = 3
        getcontext().rounding = ROUND_HALF_UP
        # 遍历所有订单
        for dd in dingdan_this_month:
            # 获取当前订单关联的所有产品
            chanpin_set = dd.ddchanpin.all()  # 假设ddchanpin是订单到产品的多对多字段
            # 遍历当前订单的所有产品，并累加cbj值
            for chanpin in chanpin_set:
                if dd.kaipiaoif==1:
                    bb=chanpin.cbj
                    xx=Decimal(chanpin.jiage)* Decimal(0.03)
                    chanpin.cbj= chanpin.cbj + xx
                    print(f'{xx}税费')
                    print(f'{chanpin.cbj}产品成本价（带税）—--{bb}不带税成本价')
                    total_cbj += chanpin.cbj
                else:
                    print(f'{chanpin.cbj}产品成本价')
                    total_cbj += chanpin.cbj

        new_ddjine_this_month_after_cbj = (new_ddjine_this_month - total_cbj) / 2
        print(f'new_ddjine_this_month_after_cbj:{new_ddjine_this_month_after_cbj}-----{new_ddjine_this_month}')# 计算订单毛利

        #new_ddmaoli_this_month=ddml
        context['new_customers_this_month'] = new_customers_this_month
        context['new_dingdan_this_month'] = new_dingdan_this_month
        context['new_ddjine_this_month'] = new_ddjine_this_month
        context['new_ddjine_this_month_after_cbj'] = new_ddjine_this_month_after_cbj
        if messages.get_messages(request):  # 如果有消息
            context['messages'] = messages.get_messages(request)  # 将消息添加到上下文中
        return render(request, 'home.html', context)
    else:
        messages.error(request, "会话已过期，请重新登录")  # 添加会话过期提示
        return redirect('login')


class New_List(LoginRequiredMixin,ListView):
    model = new
    #paginate_by = 5
    template_name = 'newlist.html'
    context_object_name = 'newlist'
    # def get_queryset(self):
    #     qs = super().get_queryset()
    #     return qs.filter(faburen=self.request.user)

class New_Detail(DetailView):
    model = new
    template_name = 'new-detail.html'
    context_object_name = 'new'
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['bigtitle'] = '资讯列表'
        return context

